package com.woniuxy.yoga.business.web.controller;


import cn.hutool.core.bean.BeanUtil;
import com.woniuxy.yoga.business.model.dto.businessaccount.BusinessAccountLoginDTO;
import com.woniuxy.yoga.business.model.dto.businessaccount.BusinessAccountSelDTO;
import com.woniuxy.yoga.business.model.dto.businessaccount.BusinessLoginPhoneDTO;
import com.woniuxy.yoga.business.model.dto.businessaccount.BusinessLoginToken;
import com.woniuxy.yoga.business.model.form.businessaccount.*;
import com.woniuxy.yoga.business.model.param.businessaccount.*;
import com.woniuxy.yoga.business.permission.Permission;
import com.woniuxy.yoga.business.service.BusinessAccountService;
import com.woniuxy.yoga.commons.core.model.PageInfo;
import com.woniuxy.yoga.commons.core.model.Result;
import com.woniuxy.yoga.commons.core.util.JWTUtil;
import com.woniuxy.yoga.commons.oss.util.OSSUtil;
import com.woniuxy.yoga.commons.redis.util.RedisUtil;
import com.woniuxy.yoga.commons.web.log.YogaLog;
import com.woniuxy.yoga.commons.web.util.UpLoadFileUtil;
import com.woniuxy.yoga.commons.web.util.WebUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.EOFException;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 商家账号表 前端控制器
 * </p>
 *
 * @author 韦用文, 刘存益, 郎腾霄
 * @since 2023年11月30日
 */
@RestController
@RequestMapping("/businessAccount")
@Api(tags = "商家账号相关接口")
public class BusinessAccountController {


    @Autowired
    private BusinessAccountService businessAccountService;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private OSSUtil ossUtil;
    @Autowired
    private UpLoadFileUtil upLoadFileUtil;

    /**
     * 商家发送注册验证码
     *
     * @param form 发送验证码参数对象
     * @return
     */
    @PostMapping("/sendRegisterCode.bu")
    @ApiOperation("发送注册验证码")
    @YogaLog("商家发送注册验证码")
    public Result<String> sendRegisterCode(@Valid @RequestBody BusinessRegisterPhoneForm form) throws Exception {
        businessAccountService.sendRegisterCode(BeanUtil.toBean(form, BusinessRegisterPhoneParam.class));
        return Result.getResult(String.class).setMessage("发送验证码成功");
    }

    /**
     * 商家手机验证码注册操作
     *
     * @param form
     * @return
     */
    @PostMapping("/businessRegister.bu")
    @ApiOperation("商家注册账号操作")
    @YogaLog("商家注册账号")
    public Result<Integer> businessRegister(@Valid @RequestBody BusinessRegisterForm form) throws Exception {
        Integer accountId = businessAccountService.businessRegister(BeanUtil.toBean(form, BusinessRegisterParam.class));
        return Result.getResult(Integer.class).setMessage("商家账号注册成功").setData(accountId);
    }

    /**
     * 商家账号登录
     *
     * @param form
     * @param resp
     * @return
     */
    @PostMapping("/businessLoginByName.bu")
    @ApiOperation("商家账号密码登录")
    @YogaLog("商家账号密码登录")
    public Result<BusinessAccountLoginDTO> businessLoginByName(@Valid @RequestBody BusinessAccountLoginForm form, HttpServletResponse resp) throws Exception {
        BusinessAccountLoginDTO dto = businessAccountService.businessLoginByName(BeanUtil.toBean(form, BusinessAccountLoginParam.class));
        BusinessLoginToken businessLoginToken = new BusinessLoginToken();
        businessLoginToken.setBusinessId(dto.getAccountId());
        businessLoginToken.setBusinessName(dto.getAccountName());
        Map<String, Object> map = BeanUtil.beanToMap(businessLoginToken);
        //生成jwt令牌
        String businessToken = JWTUtil.createBusinessToken(map, 30);
        String refreshToken = JWTUtil.createBusinessToken(map, 3 * 24 * 60);
        redisUtil.set(businessToken, refreshToken, 3 * 24 * 60 * 60L);
        resp.setHeader("authen_token", businessToken);
        resp.setHeader("Access-Control-Expose-Headers", "authen_token");
        if (dto == null) return Result.getResult(BusinessAccountLoginDTO.class).setMessage("登录失败");
        return Result.getResult(BusinessAccountLoginDTO.class).setMessage("商家登录成功").setData(dto);
    }

    /**
     * 商家发送登录验证码
     *
     * @param form
     * @return
     */
    @PostMapping("/sendLoginCode.bu")
    @ApiOperation("商家发送登录验证码")
    @YogaLog("商家发送登录验证码")
    public Result<String> sendLoginCode(@Valid @RequestBody BusinessLoginSendForm form) throws Exception {
        businessAccountService.sendLoginCode(BeanUtil.toBean(form, BusinessLoginSendParam.class));
        return Result.getResult(String.class).setMessage("验证码发送成功");
    }

    /**
     * 商家手机验证码登录
     *
     * @param form
     * @return
     */
    @PostMapping("/businessLoginByPhone.bu")
    @ApiOperation("商家手机验证码登录")
    @YogaLog("商家手机验证码登录")
    public Result<BusinessLoginPhoneDTO> businessLoginByPhone(@Valid @RequestBody BusinessLoginPhoneForm form) throws Exception {
        //获取登录地址ip
        String addr = WebUtil.getRequest().getRemoteAddr();
        BusinessLoginPhoneParam param = BeanUtil.toBean(form, BusinessLoginPhoneParam.class);
        param.setLoginAddress(addr);
        BusinessLoginPhoneDTO dto = businessAccountService.businessLoginByPhone(param);
        BusinessLoginToken businessLoginToken = new BusinessLoginToken();
        businessLoginToken.setBusinessId(dto.getAccountId());
        businessLoginToken.setBusinessName(dto.getAccountName());
        Map<String, Object> map = BeanUtil.beanToMap(businessLoginToken);
        //生成jwt令牌
        String businessToken = JWTUtil.createBusinessToken(map, 30);
        String refreshToken = JWTUtil.createBusinessToken(map, 3 * 24 * 60);
        redisUtil.set(businessToken, refreshToken, 3 * 24 * 60 * 60L);
        //通过响应头将短时的token响应给客户端
        WebUtil.getResponse().setHeader("authen_token", businessToken);
        WebUtil.getResponse().setHeader("Access-Control-Expose-Headers", "authen_token");
        return Result.getResult(BusinessLoginPhoneDTO.class).setMessage("商家登录成功").setData(dto);
    }

    /**
     * 上传商家头像（也可以用来测试）
     * @param image
     * @return
     * @throws Exception
     */
    @PostMapping("/addBusinessHeader.bu")
    @ApiOperation("上传图片")
    @YogaLog("上传图片")
    public Result<String> addBusinessHeader(MultipartFile image) throws Exception {
        if (image==null) throw new Exception("传入图片不能为空");
        //获取上传图片的文件名
        String filename = image.getOriginalFilename();
        //获取图片的类型
        String name = filename.substring(filename.lastIndexOf(".")+1);
        //调用API上传
        String imagePath = ossUtil.uploadFile(image.getInputStream(),name);
        return Result.getResult(String.class).setData(imagePath).setMessage("上传图片成功");
    }

    /**
     * 删除已上传的图片
     * @param path
     * @return
     * @throws Exception
     */
    @PostMapping("/removeUpLoadFile.bu")
    @ApiOperation("删除已上传的图片")
    @YogaLog("删除已上传的图片")
    public Result<Boolean> removeUpLoadFile(String path) throws Exception {
        boolean bool = upLoadFileUtil.removeFile(path);
        return Result.getResult(Boolean.class).setData(bool).setMessage(bool?"删除成功":"删除失败");
    }

    /**
     * 商家注销操作
     * @param authen_token
     * @return
     * @throws Exception
     */
    @PostMapping("/businessDelete.bu")
    @ApiOperation("商家注销操作")
    @YogaLog("商家注销操作")
    public Result<String> businessDelete(@RequestHeader String authen_token)throws Exception{
        String refreshToken = redisUtil.get(authen_token);
        Integer businessId = JWTUtil.getBusinessId(refreshToken);
        businessAccountService.businessDelete(businessId);
        return Result.getResult(String.class).setMessage("注销成功");
    }

    /**
     * 查询商家信息
     * @param authen_token
     * @return
     */
    @PostMapping("/selBusiness.bu")
    @ApiOperation("查询商家信息")
    @YogaLog("查询商家信息")
    public Result<BusinessAccountSelDTO> selBusiness(@RequestHeader String authen_token) {
        String refreshToken = redisUtil.get(authen_token);
        Integer businessId = JWTUtil.getBusinessId(refreshToken);
        BusinessAccountSelDTO dto = businessAccountService.selBusiness(businessId);
        return Result.getResult(BusinessAccountSelDTO.class).setMessage("查询成功").setData(dto);
    }

    /**
     * 平台分页查询商家信息
     * @return
     */
    @PostMapping ("/selectPageBusiness.api")
    @ApiOperation("分页查询商家信息")
    @YogaLog("分页查询商家信息")
    @Permission(resources = {"/business/businessAccount/selectPageBusiness.api"})
    public Result<PageInfo> selectPageBusiness(@RequestBody SelectPageBusinessForm form){
        PageInfo pageInfo = businessAccountService.selectPageBusiness(BeanUtil.toBean(form,SelectPageBusinessParam.class));
        return Result.getResult(PageInfo.class).setData(pageInfo).setMessage("分页查询商家信息成功");
    }

    /**
     * 修改商家昵称
     * @param authen_token
     * @return
     */
    @PostMapping("/changeNickName.bu")
    @ApiOperation("修改商家昵称")
    @YogaLog("修改商家昵称")
    public Result<String> changeNickName(@Valid@RequestBody ChangeNickNameForm form, @RequestHeader String authen_token) {
        String refreshToken = redisUtil.get(authen_token);
        Integer businessId = JWTUtil.getBusinessId(refreshToken);
        ChangeNickNameParam param = BeanUtil.toBean(form, ChangeNickNameParam.class);
        param.setAccountId(businessId);
        businessAccountService.changeNickName(param);
        return Result.getResult(String.class).setMessage("修改成功");
    }

    /**
     * 检查商家输入的密码是否正确
     * @param businessPass
     * @param authen_token
     * @return
     */
    @GetMapping("/checkPassword/{businessPass}.bu")
    @ApiOperation("检查商家输入的密码是否正确")
    @YogaLog("修改密码前验证密码")
    public Result<String> checkPassword(@PathVariable("businessPass") String businessPass, @RequestHeader String authen_token) {
        String refreshToken = redisUtil.get(authen_token);
        Integer businessId = JWTUtil.getBusinessId(refreshToken);
        CheckPasswordParam param = new CheckPasswordParam();
        param.setAccountPassword(businessPass);
        param.setAccountId(businessId);
        businessAccountService.checkPassword(param);
        return Result.getResult(String.class).setMessage("商家输入密码正确（可修改密码）");
    }

    /**
     * 商家修改账号密码
     * @param form
     * @param authen_token
     * @return
     */
    @PostMapping("/changePassword.bu")
    @ApiOperation("商家修改账号密码")
    @YogaLog("商家修改账号密码")
    public Result<String> changePassword(@RequestBody ChangePasswordForm form, @RequestHeader String authen_token) {
        String refreshToken = redisUtil.get(authen_token);
        Integer businessId = JWTUtil.getBusinessId(refreshToken);
        ChangePasswordParam param = BeanUtil.toBean(form, ChangePasswordParam.class);
        param.setAccountId(businessId);
        businessAccountService.changePassword(param);
        return Result.getResult(String.class).setMessage("商家修改账号密码成功");
    }

    /**
     * 商家修改账号头像
     * @param image
     * @param authen_token
     * @return
     */
    @PostMapping("/updateHeader.bu")
    @ApiOperation("商家修改账号头像")
    @YogaLog("商家修改账号头像")
    public Result<String> updateHeader(MultipartFile image,@RequestHeader String authen_token) throws Exception {
        String refreshToken = redisUtil.get(authen_token);
        Integer businessId = JWTUtil.getBusinessId(refreshToken);
        UpdateHeaderParam param = new UpdateHeaderParam();
        param.setAccountHeader(image);
        param.setAccountId(businessId);
        businessAccountService.updateHeader(param);
        return Result.getResult(String.class).setMessage("修改账号头像成功");
    }

    /**
     * 商家退出登录
     * @param authen_token
     * @return
     */
    @PostMapping("/businessLogOut.bu")
    @ApiOperation("商家退出登录")
    @YogaLog("商家退出登录")
    public Result<String> businessLogOut(@RequestHeader String authen_token){
        redisUtil.delete(authen_token);
        return Result.getResult(String.class).setMessage("退出登录成功");
    }


}

